<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\LocationAnimalModel;
use App\V3\V3_2_7\Models\LocationLogModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LocationAnimalService
{
    public static function outInAnimal($data, $time)
    {
        DB::beginTransaction();
        try {
            if (!empty($data['animal_info'])) {
                $animalArr = json_decode(
                    $data['animal_info'],
                    true,
                    512,
                    JSON_THROW_ON_ERROR
                );
                $shelfId = 0;
                if (is_array($animalArr)) {
                    foreach ($animalArr as $val) {
                        if (!empty($val['location_id'])) {
                            $locInfo = StorageShelfLocationModel::getLocationInfo([
                                'main_id' => $data['main_id'],
                                'id' => $val['location_id'],
                                'status' => 1
                            ]);
                            if (empty($locInfo))
                                throw new \Exception('选择的盒子,不存在!');
                            $animalInfo = LocationAnimalModel::getLocationAnimalInfo([
                                'main_id' => $data['main_id'],
                                'location_id' => $val['location_id'],
                                'delete_flag' => 0,
                                'type' => 0,
                            ]);
                            $shelfName = StorageShelfModel::query()
                                ->where('id', $locInfo['shelf_id'])
                                ->value('shelf_name') ?? '';
                            $str = $val['animal_name'] ?? $animalInfo['animal_name'];
                            $arr = ['gene', 'sex', 'gram_weight', 'num'];
                            foreach ($arr as $aVal) {
                                if (isset($data[$aVal])) {
                                    $str .= '/' . $data[$aVal];
                                } else {
                                    if (!empty($animalInfo))
                                        $str .= '/' . $animalInfo[$aVal];
                                }
                            }
                            $log = [
                                'location_id' => $locInfo['id'],
                                'add_type' => 1,
                                'conent1' => $shelfName . '-' . $locInfo['location_name'],
                                'conent2' => $str,
                                'conent3' => '入库',
                                'in_out_type' => 1,
                                'log_no' => getNO('location_animal', 'log_no'),
                                'user_id' => $data['user_id'],
                                'main_id' => $data['main_id'],
                                'out_tag_id' => $data['out_tag_id'] ?? 0,
                                'remark' => $data['remark'] ?? '',
                            ];

                            if ((int)$data['in_out_type'] === 1) {//入库
                                if (!empty($animalInfo)) {
                                    throw new \Exception(
                                        '盒子：' . $locInfo['location_name'] . '的宠物：' . $animalInfo['animal_name'] . '未归档，不能多次入库！'
                                    );
                                } else {
                                    /*if (empty($val['animal_name']))
                                        throw new \Exception('盒子：' . $locInfo['location_name'] . '的宠物名称，不能为空');*/
                                    $log['log_no'] = getNO('location_animal', 'log_no');
                                    $val['log_no'] = $log['log_no'];
                                    $val['user_id'] = $data['user_id'];
                                    $val['main_id'] = $data['main_id'];
                                    $animalId = LocationAnimalModel::query()->insertGetId($val);
                                    $log['animal_id'] = $animalId;
                                    $log['conent4'] = '正常使用';
                                    StorageShelfLocationModel::query()->where([
                                        'id' => $locInfo['id']
                                    ])->update(['log_no' => $log['log_no'], 'tag_id' => 4]);
                                    StorageShelfModel::query()
                                        ->where('id', $locInfo['shelf_id'])
                                        ->update(['tag_id' => 1]);
                                }
                            }

                            if ((int)$data['in_out_type'] === 2) {//出库
                                if (empty($animalInfo))
                                    throw new \Exception(
                                        '盒子：' . $locInfo['location_name'] . ' 没有宠物，不能出库！'
                                    );
                                if (empty($animalInfo['num']) || !empty($animalInfo['type'])) {
                                    throw new \Exception(
                                        '盒子：' . $locInfo['location_name'] . '的宠物:' . $animalInfo['animal_name'] . ' 已归档，不出库！'
                                    );
                                }
                                $log['type'] = 1;
                                $log['conent3'] = '出库';
                                $log['in_out_type'] = 3;
                                $log['animal_id'] = $animalInfo['id'];
                                $log['log_no'] = $locInfo['log_no'];
                                $log['conent2'] = $str;
                                $log['type_time'] = now()->format('Y-m-d H:i:s');
                                LocationAnimalModel::query()->where([
                                    'id' => $animalInfo['id'],
                                ])->update(['type' => 1,
                                    'sell_price' => $val['sell_price'] ?? $animalInfo['sell_price']
                                ]);
                                LocationLogModel::query()->where([
                                    'location_id' => $locInfo['id'],
                                    'log_no' => $locInfo['log_no'],
                                ])->update([
                                    'type' => 1
                                ]);
                                StorageShelfLocationModel::query()->where([
                                    'id' => $locInfo['id']
                                ])->update(['tag_id' => 8]);
                                $shelfId = $locInfo['shelf_id'];
                            }
                            LocationLogModel::query()->insertGetId($log);

                        } else {
                            throw new \Exception('盒子数据有误！');
                        }
                    }
                    if ((int)$data['in_out_type'] === 2 && !empty($shelfId)) {
                        $locaIdArr = StorageShelfLocationModel::query()
                            ->where([
                                'status' => 1,
                                'shelf_id' => $shelfId,
                                'main_id' => $data['main_id']
                            ])->pluck('id')->toArray() ?? [];
                        if (!empty($locaIdArr)) {
                            $animalNum = LocationAnimalModel::query()->where([
                                'type' => 0,
                                'delete_flag' => 0,
                                'main_id' => $data['main_id']
                            ])->whereIn('location_id', $locaIdArr)->sum('num');
                            if (empty($animalNum)) {
                                StorageShelfModel::query()->where([
                                    'status' => 1,
                                    'id' => $shelfId,
                                    'main_id' => $data['main_id']
                                ])->update(['tag_id' => 3]);
                            }
                        }
                    }
                    CommonService::operateResult(
                        $data['user_id'],
                        $time,
                        $data,
                        (int)$data['in_out_type'] === 1 ? '入库' : '出库' . '成功'
                    );
                    DB::commit();
                    return success();
                }
            }
            throw new \Exception('数据有误！');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('宠物出入库异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function update($data, $time)
    {
        DB::beginTransaction();
        try {
            if (!empty($data['location_ids'])) {
                $log = [];
                $idArr = explode(',', $data['location_ids']);
                foreach ($idArr as $val) {
                    $locaInfo = StorageShelfLocationModel::query()->where([
                        'main_id' => $data['main_id'],
                        'id' => $val,
                        'status' => 1
                    ])->first();
                    $shelfInfo = StorageShelfModel::query()->where([
                        'main_id' => $data['main_id'],
                        'id' => $locaInfo['shelf_id'],
                        'status' => 1
                    ])->first();

                    $animalInfo = LocationAnimalModel::getLocationAnimalInfo([
                        'main_id' => $data['main_id'],
                        'location_id' => $val,
                        'delete_flag' => 0,
                        'type' => 0
                    ]);
                    if (empty($animalInfo))
                        throw new \Exception('盒子：' . $locaInfo['location_name'] . ',无宠物信息');
                    unset($data['location_ids']);
                    LocationAnimalModel::query()->where('id', $animalInfo['id'])->update($data);
                    $str = $data['animal_name'] ?? $animalInfo['animal_name'];
                    $arr = ['gene', 'sex', 'gram_weight', 'num'];
                    foreach ($arr as $aVal) {
                        if (isset($data[$aVal])) {
                            $str .= '/' . $data[$aVal];
                        } else {
                            $str .= '/' . $animalInfo[$aVal];
                        }
                    }
                    $log[] = [
                        'location_id' => $val,
                        'add_type' => 1,
                        'conent1' => $shelfInfo['shelf_name'] . '-' . $locaInfo['location_name'],
                        'conent2' => $str,
                        'conent3' => '变更信息',
                        //'conent4' => $locaInfo['tag_id'],
                        'in_out_type' => 4,
                        'animal_id' => $animalInfo['id'],
                        'log_no' => $locaInfo['log_no'],
                        'user_id' => $data['user_id'],
                        'main_id' => $data['main_id']
                    ];
                }
                LocationLogModel::query()->insert($log);
                DB::commit();
                return success();
            } else {
                throw new \Exception('请选择盒子！');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('修改宠物信息异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }
}
